package com.sskj.fca.ui.fragment;

import android.annotation.SuppressLint;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.TimeFormatUtil;
import com.sskj.common.util.TipMineUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.fca.R;
import com.sskj.fca.bean.RollMsg;
import com.sskj.fca.bean.RollPointsBean;
import com.sskj.fca.component.DaggerUserDataComponent;
import com.sskj.fca.presenter.RollCompareFragmentPresenter;
import com.sskj.fca.ui.roll.AutoPollAdapter;
import com.sskj.fca.ui.roll.AutoPollRecyclerView;
import com.sskj.fca.ui.roll.SmoothScrollLayoutManager;
import com.sskj.fca.util.HideUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;

/**
 * Created by QinKang on 2018/12/29.
 */

@Route(path = RConfig.APP_FRAGMENT_ROLL_COMPARE)//Roll点比大小
public class RollCompareFragment extends BaseFragment<RollCompareFragmentPresenter> {
    @BindView(R.id.tv_roll_residue_time)
    TextView tvRollResidueTime;
    //    @BindView(R.id.tv_roll_left)
//    TickerView tvRollLeft;
//    @BindView(R.id.tv_roll_center)
//    TextView tvRollCenter;
//    @BindView(R.id.tv_roll_right)
//    TextView tvRollRight;
    @BindView(R.id.tv_roll_start)
    TextView tvRollStart;
    @BindView(R.id.tv_roll_start_time)
    TextView tvRollStartTime;
    @BindView(R.id.tv_roll_countdown)
    TextView tvRollCountdown;
    @BindView(R.id.tv_roll_award)
    TextView tvRollAward;
    @BindView(R.id.recycler_roll)
    RecyclerView recyclerRoll;
    @BindView(R.id.rv_left)
    AutoPollRecyclerView rv_left;
    @BindView(R.id.rv_center)
    AutoPollRecyclerView rv_center;
    @BindView(R.id.rv_right)
    AutoPollRecyclerView rv_right;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;

    private SlimAdapter slimAdapter;
    private long second;

    private List<String> numbers = new ArrayList<>();
    private DisposableSubscriber<Long> disposableSubscriber;
    private AutoPollAdapter autoPollAdapter;
    private Disposable mDisposable;
    private int times;
    private MaterialDialog loginTip;

    @Override
    protected int getLayoutId() {
        return R.layout.app_fragment_roll_compare;
    }

    @Override
    protected RollCompareFragmentPresenter getPresenter() {
        return new RollCompareFragmentPresenter();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            mPresenter.getRollMsg();
        } else {
            if (mDisposable != null && !mDisposable.isDisposed()) {
                mDisposable.dispose();
                mDisposable = null;
            }
            DisposUtil.close(disposableSubscriber);

        }
    }

    @Override
    public void initView() {
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
        mPresenter.getRollMsg();

        initRvRoll();

        ClickUtil.click(tvRollStart, () -> {
            if (userData == null) {
                if (loginTip == null) {
                    loginTip = TipMineUtil.getTip(getActivity(), "请先登录", "去登录", () -> {
                        ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
                    });
                }
                loginTip.show();
                return;
            }
            if (times > 0) {
                mPresenter.getRollPoints();
            } else {
                ToastUtil.showShort("您没有游戏参与次数");
            }
        });

        recyclerRoll.setLayoutManager(new LinearLayoutManager(getActivity()));
        slimAdapter = SlimAdapter.create().register(R.layout.app_recy_item_roll_compare, new SlimInjector<RollMsg.RankBean>() {
            @Override
            public void onInject(RollMsg.RankBean data, IViewInjector injector, List payloads) {
                if (slimAdapter.getData().indexOf(data) % 2 == 1) {
                    injector.background(R.id.llBg, ContextCompat.getDrawable(App.INSTANCE, R.drawable.app_bg_7d7));
                } else {
                    injector.backgroundColor(R.id.llBg, ContextCompat.getColor(App.INSTANCE, R.color.app_696));
                }
                String palyerName = data.getNickname();
                if (HideUtil.isInteger(palyerName)) {
                    if (palyerName.length() == 11) {
                        palyerName = HideUtil.getPhoneHide(palyerName);
                    }
                }
                injector.text(R.id.tv_item_sort, data.getRank())
                        .text(R.id.tv_item_player, palyerName)
                        .text(R.id.tv_item_count, data.getRoll_num())
                        .text(R.id.tv_item_money, data.getAward_qc());
            }
        }).attachTo(recyclerRoll).updateData(new ArrayList());
//        Flowable.rangeLong(0, 5)
//                .map(i -> i + "")
//                .toList()
//                .subscribe(strings -> slimAdapter.updateData(strings));
    }

    private void initRvRoll() {
        List<String> datas = new ArrayList<>();
        for (int i = 0; i <= 9; i++) {
            datas.add(i + "");
        }
        autoPollAdapter = new AutoPollAdapter(datas);
        rv_left.setLayoutManager(new SmoothScrollLayoutManager(getActivity()));
        rv_left.setAdapter(autoPollAdapter);
        rv_center.setLayoutManager(new SmoothScrollLayoutManager(getActivity()));
        rv_center.setAdapter(autoPollAdapter);
        rv_right.setLayoutManager(new SmoothScrollLayoutManager(getActivity()));
        rv_right.setAdapter(autoPollAdapter);
    }

    public void updataUI(RollMsg rollMsg) {
        times = Integer.parseInt(rollMsg.getTimes());
        if (Integer.parseInt(rollMsg.getSy_sec()) > 0) {
            tvRollStart.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.app_bg_7d7));
            tvRollStart.setClickable(false);
        }
        startCountDown(Integer.parseInt(rollMsg.getSy_sec()));
        tvRollResidueTime.setText(String.format(App.INSTANCE.getString(R.string.app_roll_last_times), rollMsg.getTimes()));
        tvRollAward.setText(String.format(App.INSTANCE.getString(R.string.app_today_award), rollMsg.getUser_award()));
        tvRollStartTime.setText(String.format(App.INSTANCE.getString(R.string.app_roll_start_time), rollMsg.getStart(), rollMsg.getEnd()));
        if (slimAdapter != null) {
            slimAdapter.updateData(rollMsg.getRank());
        }
    }

    @SuppressLint("StringFormatMatches")
    public void setRollPoints(RollPointsBean rollPointsBean) {
        if (TextUtils.isEmpty(rollPointsBean.getOne())
                || TextUtils.isEmpty(rollPointsBean.getTwo())
                || TextUtils.isEmpty(rollPointsBean.getThree())) {
            ToastUtil.showShort("获取游戏信息失败");
            return;
        }
        times--;
        tvRollResidueTime.setText(String.format(App.INSTANCE.getString(R.string.app_roll_last_times), times));
        rv_left.start();
        rv_center.start();
        rv_right.start();
        Observable.timer(3, TimeUnit.SECONDS)
                .subscribe(aLong -> {
                    rv_left.stop();
                    rv_center.stop();
                    rv_right.stop();
                });
        rv_left.setRunningStop(() -> {
            int lastPosition = autoPollAdapter.getLastPosition();
            if (lastPosition % 10 <= Integer.parseInt(rollPointsBean.getOne())) {
                lastPosition += Integer.parseInt(rollPointsBean.getOne()) - lastPosition % 10;
            } else {
                lastPosition += 10 - lastPosition % 10 + Integer.parseInt(rollPointsBean.getOne());
            }
            rv_left.smoothScrollToPosition(lastPosition);
        });
        rv_center.setRunningStop(() -> {
            int lastPosition = autoPollAdapter.getLastPosition();
            if (lastPosition % 10 <= Integer.parseInt(rollPointsBean.getTwo())) {
                lastPosition += Integer.parseInt(rollPointsBean.getTwo()) - lastPosition % 10;
            } else {
                lastPosition += 10 - lastPosition % 10 + Integer.parseInt(rollPointsBean.getTwo());
            }
            System.out.println(lastPosition);
            rv_center.smoothScrollToPosition(lastPosition);
        });
        rv_right.setRunningStop(() -> {
            int lastPosition = autoPollAdapter.getLastPosition();
            if (lastPosition % 10 <= Integer.parseInt(rollPointsBean.getThree())) {
                lastPosition += Integer.parseInt(rollPointsBean.getThree()) - lastPosition % 10;
            } else {
                lastPosition += 10 - lastPosition % 10 + Integer.parseInt(rollPointsBean.getThree());
            }
            System.out.println(lastPosition);
            rv_right.smoothScrollToPosition(lastPosition);
        });
    }

    private void startCountDown(int lastSeconds) {
        second = lastSeconds;
        Observable.interval(1, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {

                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        second--;
                        if (second < 0) {
                            mDisposable.dispose();
                            tvRollStart.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.app_bt_bg));
                            tvRollStart.setClickable(true);
//                            Toast.makeText(getActivity(), "倒计时结束", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        tvRollCountdown.setText(TimeFormatUtil.second2TimeSecond(second));
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }
}
